package com.nf.health.app.fragment;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.hyphenate.chat.EMClient;
import com.nf.health.app.MyApplication;
import com.nf.health.app.R;
import com.nf.health.app.login.activity.LoginActivity;
import com.nf.health.app.mine.activity.SettingActivity;
import com.nf.health.app.core.HttpActionHandle;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.http.VolleyErrorHelper;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.JsonUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;

import butterknife.ButterKnife;

public class IBaseFragment extends Fragment implements HttpActionHandle{


	protected static final int SETTING_ID = 0x99999999;
	protected String TAG = IBaseFragment.class.getSimpleName();
	protected View rootView;
	private ViewGroup mContentGroup;
	private ViewGroup mLoading;
	private ViewGroup mDataError;
	private int mLoadingCount = 0; // 计数器当前耗时操作的数量
	protected RequestProvider provider;
	protected TextView tv_no_data;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		TAG = this.getClass().getSimpleName();
		provider = new RequestProvider(this);
		//<merge /> can be used only with a valid ViewGroup root and attachToRoot=true
		rootView = inflater.inflate(R.layout.layout_fragment_base, null);
		mContentGroup = (ViewGroup) rootView.findViewById(R.id.l_my_activity_base_context);
		mLoading = (ViewGroup) rootView.findViewById(R.id.l_my_activity_base_loading);
		mDataError = (ViewGroup) rootView.findViewById(R.id.l_my_activity_base_data_error);
		tv_no_data = (TextView) rootView.findViewById(R.id.tv_no_data);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mDataError.findViewById(R.id.l_error_data_btn).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						hideDataError();
						onRefresh();
					}

				});
//		MyApplication.getRefWatcher(getActivity()).watch(this);
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}
	/**
	 * 继承者刷新
	 */
	protected void onRefresh() {
	}
	
	/**
	 * 给内容区添加内容
	 * 
	 * @param v
	 */
	protected final void addViewFillInRoot(View v) {
		mContentGroup.addView(v, LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
	}

	/**
	 * 给内容区添加内容
	 * 
	 * @param nRes
	 */
	protected final void addViewFillInRoot(final int nRes) {
		rootView = getLayoutInflater(nRes);
		addViewFillInRoot(rootView);
	}
	
	
	/**
	 * 弱显示3S
	 * 
	 * @param text
	 */
	protected final void showToast(String text) {
		try {
			Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			LogUtil.exception(e);
		}
	}

	protected final void showToast(final int nRes) {
		String t = "";
		if (nRes > 0) {
			t = getResources().getString(nRes);
		}
		showToast(t);
	}

	/**
	 * 显示正载加载
	 */
	protected final void showDataError() {
		mDataError.setVisibility(View.VISIBLE);
	}
	
	/**
	 * 不显示加载项
	 */
	protected final void hideDataError() {
		mDataError.setVisibility(View.GONE);
	}
	/**
	 * 显示正载加载
	 */
	protected final void showNoData() {
		tv_no_data.setVisibility(View.VISIBLE);
	}
	
	/**
	 * 不显示加载项
	 */
	protected final void hideNoData() {
		tv_no_data.setVisibility(View.GONE);
	}
	/**
	 * 显示正载加载
	 */
	protected final void showLoading() {
		mLoadingCount++;
		mLoading.setVisibility(View.VISIBLE);
	}
	/**
	 * 显示正载加载
	 */
	protected final void showLoading(String msg) {
		mLoadingCount++;
		TextView tv_msg = (TextView) mLoading.findViewById(R.id.tv_message);
		tv_msg.setVisibility(View.VISIBLE);
		tv_msg.setText(msg);
		mLoading.setVisibility(View.VISIBLE);
	}

	/**
	 * 不显示加载项
	 */
	protected final void hideLoading() {
		this.hideLoading(false);
	}
	/**
	 * 不显示加载项
	 * 
	 * @param bForceHide
	 *            是否强制隐藏
	 */
	protected final void hideLoading(boolean bForceHide) {
		mLoadingCount--;
		if (bForceHide) {
			mLoadingCount = 0;
		}
		if (mLoadingCount <= 0) {
			mLoading.setVisibility(View.GONE);
		}
	}
	
	/**
	 * 生成view
	 * 
	 * @param nRes
	 * @return
	 */
	protected final View getLayoutInflater(final int nRes) {
		return LayoutInflater.from(getActivity()).inflate(nRes, null);
	}

	@Override
	public void handleActionStart(String actionName, Object object) {
		showLoading();
	}

	@Override
	public void handleActionFinish(String actionName, Object object) {
		hideLoading();
	}

	@Override
	public void handleActionError(String actionName, String response, VolleyError error) {
		if (TextUtils.isEmpty(response)) {
			//处理error
			showToast(VolleyErrorHelper.getMessage(error));
		} else {
			//处理response
			String code = JsonUtils.getKey2Value(response, "code");
			if("2002".equals(code)){
				PreferenceHelper.putBoolean(PreferenceHelper.ISLOGIN, false);
				showToast("登录失效，请重新登录");
				//未登录
				ActivityUtils.skipActivity(getActivity(), LoginActivity.class);
				EMClient.getInstance().logout(true);
			}else{
				if(TextUtils.isEmpty(JsonUtils.getFiledData(response,"msg"))){

				}else{
					showToast(JsonUtils.getFiledData(response, "msg"));
				}
			}
		}
	}

	@Override
	public void handleActionSuccess(String actionName, Object object) {
		try {
			//处理response
			String code = JsonUtils.getKey2Value(object.toString(), "code");
			if ("9999".equals(code)) {
				ActivityUtils.showActivity(getActivity(), SettingActivity.class);//个人设置
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		ButterKnife.unbind(this);
	}

	@Override
	public void onDestroy() {
        MyApplication.getRefWatcher(getActivity()).watch(this);
		super.onDestroy();
	}
}
